package io.renren.modules.biz.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.biz.entity.CenterEntity;
import io.renren.modules.biz.entity.MemberEntity;
import io.renren.modules.biz.entity.RoomEntity;
import io.renren.modules.biz.service.CenterService;
import io.renren.modules.biz.service.GrabPacketService;
import io.renren.modules.biz.service.MemberService;
import io.renren.modules.biz.service.RoomService;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * 游戏房间
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-09-03 14:51:31
 */
@RestController
@RequestMapping("biz/room")
public class RoomController {
	@Autowired
	private MemberService memberService;

	@Autowired
	private RoomService roomService;

	@Autowired
	private CenterService centerService;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private GrabPacketService grabPacketService;

	/**
	 * 列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/list")
	@RequiresPermissions("biz:room:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = roomService.queryPage(params);
		List<RoomEntity> list = (List<RoomEntity>) page.getList();
		if (CollectionUtils.isNotEmpty(list)) {
			List<String> serverList = redisUtils.get("SERVER_LIST", List.class);
			for (RoomEntity roomEntity : list) {
				CenterEntity entity = centerService.selectOne(new EntityWrapper<CenterEntity>().setSqlSelect("center_name").eq("id", roomEntity.getCenterId()));
				roomEntity.setCenterName(entity.getCenterName());
				roomEntity.setRealPersonOnline(totalOnlineUsersByRoom(serverList, roomEntity.getId()));
				String robotProfit = redisUtils.get("PLATFORM_ROOM_ROBOT_COUNT_" + roomEntity.getId());
				if (robotProfit == null) {
					roomEntity.setRobotProfit(grabPacketService.robotProfitByRoomId(roomEntity.getId(), null));// 房间机器人盈利
					redisUtils.set("PLATFORM_ROOM_ROBOT_COUNT_" + roomEntity.getId(), roomEntity.getRobotProfit(), 300);
				} else {
					roomEntity.setRobotProfit(Double.valueOf(robotProfit));// 房间机器人盈利
				}
			}
		}
		return R.ok().put("page", page).put("centerList", centerService.selectList(new EntityWrapper<CenterEntity>().setSqlSelect("id", "center_name")));
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("biz:room:info")
	public R info(@PathVariable("id") Integer id) {
		RoomEntity room = roomService.selectById(id);

		return R.ok().put("room", room);
	}

	/**
	 * 保存
	 */
	@SysLog("房间添加")
	@RequestMapping("/save")
	@RequiresPermissions("biz:room:save")
	public R save(@RequestBody RoomEntity room) {
		ValidatorUtils.validateEntity(room);
		Assert.isTrue(room.getMaxAmount() % room.getMinAmount() == 0, "最大金额必须是最小金额的倍数");
		if (room.getIsVip() == ProjectConstant.COMMON_YES) {
			Assert.hasText(room.getVipRoomPwd(), "VIP房间密码不能为空");
			Assert.notNull(room.getVipExpireTime(), "VIP房间过期时间为空");
			Assert.isTrue(roomService.selectCount(new EntityWrapper<RoomEntity>().eq("vip_room_pwd", room.getVipRoomPwd())) == 0, "房间密码重复,请更换密码");
		} else {
			room.setVipRoomPwd(null);
			room.setVipExpireTime(null);
		}

		if (room.getVipMemberId() != null) {
			Assert.isTrue(memberService.selectCount(new EntityWrapper<MemberEntity>().eq("id", room.getVipMemberId())) == 1, "VIP房间管理员不存在");
		}

		if (room.getEnableRobot() == ProjectConstant.COMMON_NO) {
			room.setPointTime(null);
			room.setLossLimit(null);
			room.setProfitLimit(null);
			room.setPointTime(null);
		}

		if (room.getProfitLimit() != null && room.getLossLimit() != null) {
			Assert.isTrue(room.getProfitLimit() > room.getLossLimit(), "最大盈利必须大于最大亏损");
		}
		if ((room.getProfitLimit() != null || room.getLossLimit() != null) && room.getPointTime() == null) {
			room.setPointTime(new Date());
		}

		room.setCreateTime(new Date());
		roomService.insert(room);
		redisUtils.delete("GAME_ROOMS");// 清空缓存房间信息
		return R.ok();
	}

	/**
	 * 修改
	 */
	@SysLog("房间修改")
	@RequestMapping("/update")
	@RequiresPermissions("biz:room:update")
	public R update(@RequestBody RoomEntity room) {
		ValidatorUtils.validateEntity(room);
		Assert.isTrue(room.getMaxAmount() % room.getMinAmount() == 0, "最大金额必须是最小金额的倍数");
		if (room.getIsVip() == ProjectConstant.COMMON_YES) {
			Assert.hasText(room.getVipRoomPwd(), "VIP房间密码不能为空");
			Assert.notNull(room.getVipExpireTime(), "VIP房间过期时间不能为空");
			Assert.isTrue(roomService.selectCount(new EntityWrapper<RoomEntity>().eq("vip_room_pwd", room.getVipRoomPwd()).ne("id", room.getId())) == 0, "房间密码重复,请更换密码");
		} else {
			room.setVipRoomPwd(null);
			room.setVipExpireTime(null);
		}

		if (room.getVipMemberId() != null) {
			Assert.isTrue(memberService.selectCount(new EntityWrapper<MemberEntity>().eq("id", room.getVipMemberId())) == 1, "VIP房间管理员不存在");
		}

		if (room.getEnableRobot() == ProjectConstant.COMMON_NO) {
			room.setPointTime(null);
			room.setLossLimit(null);
			room.setProfitLimit(null);
			room.setPointTime(null);
		}

		if (room.getProfitLimit() != null && room.getLossLimit() != null) {
			Assert.isTrue(room.getProfitLimit() > room.getLossLimit(), "最大盈利必须大于最大亏损");
		}

		if ((room.getProfitLimit() != null || room.getLossLimit() != null) && room.getPointTime() == null) {
			room.setPointTime(new Date());
		}

		roomService.updateAllColumnById(room);
		redisUtils.delete("GAME_ROOMS");// 清空缓存房间信息
		return R.ok();
	}

	/**
	 * 启用/禁用
	 */
	@SysLog("房间启用/禁用")
	@RequestMapping("/changeStatus")
	@RequiresPermissions("biz:center:update")
	public R changeStatus(Integer status, Long[] ids) {
		Assert.notNull(status, "参数异常[status]");
		Assert.notNull(ids, "machineIds is null");
		Assert.noNullElements(ids, "参数异常[machineIds]");
		RoomEntity entity = new RoomEntity();
		entity.setStatus(status);
		roomService.update(entity, new EntityWrapper<RoomEntity>().in("id", ids));
		redisUtils.delete("GAME_ROOMS");// 清空缓存房间信息
		return R.ok();
	}

	/**
	 * 当前房间在线用户
	 * 
	 * @param serverList
	 * @param roomId
	 * @return
	 */
	private int totalOnlineUsersByRoom(List<String> serverList, Long roomId) {
		int total = 0;
		if (CollectionUtils.isNotEmpty(serverList)) {
			for (String uid : serverList) {
				String count = redisUtils.get("ONLINE_USERS_" + uid + "_" + roomId);
				if (count == null) {
					continue;
				}
				total += Integer.parseInt(count);
			}
		}
		return total;
	}
}
